﻿#pragma once
namespace My_Priority_Queue
{
	//仿函数(可以来自己设置比较方式)
	template<class T>
	class Less
	{
	public:
		bool operator()(const T& x,const T& y)
		{
			return x < y;
		}
	};

	template<class T>
	class Greater
	{
	public:
		bool operator()(const T& x, const T& y)
		{
			return x > y;
		}
	};

	//大堆/小堆
	template<class T,class Container = vector<T>,class Compare = Less<T>>
	class priority_queue
	{
	public:
		priority_queue()
		{}
		template <class InputIterator>
		priority_queue(InputIterator first,InputIterator last)
			:_Con(first,last)
		//建堆
		{
			for (int i = (_Con.size() - 2) / 2; i >= 0; --i)
			{
				AdjustDown(i);
			}
		}
		 
		void AdjustUp(int child)
		{
			Compare Cmp;
			int parent = (child-1) / 2;
			while (child > 0)
			{
				//if (_Con[parent] < _Con[child])	//Less
				//if (_Con[parent] > _Con[child])	//Greater
				if (Cmp(_Con[parent], _Con[child]))
				{
					swap(_Con[child], _Con[parent]);
					child = parent;
					parent = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}
		void AdjustDown(int parent)
		{
			Compare Cmp;
			int child = parent * 2 + 1;//假设为左孩子
			while (child < _Con.size())
			{
				//改变为右孩子
				//if ((child + 1 < _Con.size()) && (_Con[child] < _Con[child + 1]))
				if ((child + 1 < _Con.size()) && Cmp(_Con[child] , _Con[child + 1]))
				{
					++child;
				}
				//if (_Con[parent] < _Con[child])	//Less
				//if (_Con[parent] > _Con[child])	//Greater
				if (Cmp(_Con[parent], _Con[child]))
				{
					swap(_Con[child], _Con[parent]);
					parent = child;
					child = parent * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}
		T& top()
		{
			return _Con[0];
		}
		void push(const T& x)
		{
			_Con.push_back(x);
			AdjustUp(_Con.size()-1);
		}
		void pop()
		{
			swap(_Con[0], _Con[_Con.size() - 1]);
			_Con.pop_back();
			AdjustDown(0);
		}
		bool empty()
		{
			return _Con.empty();
		}
		size_t size()
		{
			return _Con.size();
		}
	private:
		Container _Con;
	};

}